'use strict';
const BaseService = require('./base');
const moment = require('moment');
const StringUtil = require('../utils/StringUtil');
const Constant = require('../config/Constant');
const OperatorType = require('../config/OperatorType');
const ResponseUtil = require('../utils/ResponseUtil');
const RCEM = require('../utils/ResultCodeEnumMsg');


class UserService extends BaseService {

    async selectPureByPrimaryKey(id) {
        let sql = 'select * from t_user where id = ?';
        let result = await this.executeSqlFirst(sql, [id]);
        return result;
    }

    async getUserInfo(){
        let loginUserInfo = this.ctx.getLoginInfo();
        let operatorType = loginUserInfo.operatorType;
        let operatorId = loginUserInfo.operatorId;
        let createBy = loginUserInfo.createBy;

        const user = await this.selectPureByPrimaryKey(operatorId);
        if(!user){
            return null;
        }
        if(user.status !=0){
            return ResponseUtil.resError('该用户已被禁止登录');
        }

        let sql = 'select * from t_user_kyc where user_id=? and status=1 and valid=1';
        const kyc = await this.executeSqlFirst(sql,[operatorId]);
        if(kyc){
            user.isKyc = 1;
        }else{
            user.isKyc = 0;
        }
        sql = 'select * from t_user_info where user_id=?';
        const userInfo = await this.executeSqlFirst(sql,[operatorId]);
        if(userInfo){
            user.isBaseInfo = userInfo.isBaseInfo;
            user.isContactPerson = userInfo.isContactPerson;
        }

        sql = 'select * from t_user_bank where user_id=? and valid=1';
        const bank = await this.executeSqlFirst(sql,[operatorId]);
        if(bank){
            user.isBank = 1;
        }else{
            user.isBank = 1;
        }
        return user;
    }


    async getUserInfoByUserId(userId) {
        let sql = 'select * from t_user_info where user_id = ?';
        let result = await this.executeSqlFirst(sql, [userId]);
        return result;
    }

    async userKyc() {
        let loginUserInfo = this.ctx.getLoginInfo();
        let operatorType = loginUserInfo.operatorType;
        let operatorId = loginUserInfo.operatorId;
        let createBy = loginUserInfo.createBy;
        let {idcardFront, idcardBack, name, sex, idcard, contactAddress, idcardValidDate} = this.ctx.request.body;

        if (!idcardFront || !idcardBack || !name || !sex || !idcard || !contactAddress) {
            return ResponseUtil.resError('参数错误');
        }

        let sql0 = 'select * from t_user_kyc where status=1 and valid=1 and user_id=?';
        let kycInfo = await this.executeSqlFirst(sql0,[operatorId]);
        if(kycInfo){
            return ResponseUtil.resError('身份信息已添加');
        }

        let params = {
            id:StringUtil.getUUIDV2(),
            user_id: operatorId,
            idcard_front: idcardFront,
            idcard_back: idcardBack,
            name: name,
            sex: sex,
            idcard: idcard,
            contact_address: contactAddress,
            idcard_valid_date: new Date(idcardValidDate),
            status: 1,
            valid: 0
        };

        await this.executeInsert('t_user_kyc', params);

        let sql = 'update t_user set name=? where id=?';
        await this.executeSqlSucc(sql,[name,operatorId]);

        return 1;
    }


    async userBaseInfo(){
        let loginUserInfo = this.ctx.getLoginInfo();
        let operatorType = loginUserInfo.operatorType;
        let operatorId = loginUserInfo.operatorId;
        let createBy = loginUserInfo.createBy;
        let body = this.ctx.request.body;

        const userInfo = await this.getUserInfoByUserId(operatorId);

        let params = {
            user_id:operatorId,
            study:body.study,
            education:body.education,
            occupation_type:body.occupationType,
            monthly_income:body.monthlyIncome,
            sesame_points:body.sesamePoints,
            wechat_id:body.wechatId,
            email:body.email,
            work_unit:body.workUnit,
            is_base_info:1
        };

        if(userInfo){
            params.id = userInfo.id;
            delete params.user_id;
            await this.executeUpdate('t_user_info',params);
        }else{
            params.id = StringUtil.getUUIDV2();
            await this.executeInsert('t_user_info',params);
        }

        let sql = 'update t_user set email=? where id=?';
        await this.executeSqlSucc(sql,[body.email,operatorId]);

        return 1;
    }

    async contactPerson(){
        let loginUserInfo = this.ctx.getLoginInfo();
        let operatorType = loginUserInfo.operatorType;
        let operatorId = loginUserInfo.operatorId;
        let createBy = loginUserInfo.createBy;
        let body = this.ctx.request.body;

        const userInfo = await this.getUserInfoByUserId(operatorId);

        let params = {
            user_id:operatorId,
            contact_person1:body.contactPerson1,
            c_relation1:body.cRelation1,
            c_phone1:body.cPhone1,
            contact_perso2:body.contactPerson2,
            c_relation2:body.cRelation2,
            c_phone2:body.cPhone2,
            is_contact_person:1
        };

        if(userInfo){
            params.id = userInfo.id;
            delete params.user_id;
            await this.executeUpdate('t_user_info',params);
        }else{
            params.id = StringUtil.getUUIDV2();
            await this.executeInsert('t_user_info',params);
        }
        return 1;

    }



    async insertUser($user, conn) {
        let sql = 'select * from t_user where openid=? ';
        let user = await this.executeSqlFirst(sql, [$user.openid]);
        let userId = 0;
        let status = 0;
        if(user){
            userId = user.id;
            status = user.status;
            let sql = 'update t_user set ip=?,ip_local=? where id=? ';
            await this.executeSqlSucc(sql, [this.ctx.getIP(), this.ctx.getIpLocal(), user.id]);
        }else{
            const userNo = await this.ctx.getUserNo();

            const uid = StringUtil.getUUID();
            let userObj = {
                id: uid,
                name: userNo,
                openid: $user.openid,
                unionid: $user.unionid,
                avatar_url: headimgurl,
                gender: 0,
                country: 'zh',
                province: '',
                city: '',
                user_no: userNo,
                ip: this.ctx.getIP(),
                ip_local: this.ctx.getIpLocal(),
                status: 0
            };
            this.ctx.app.logger.info('insertUser user', userObj);
            let insertUserResult = await this.executeInsert('t_user', userObj, conn);
            userId = uid;
            return 0;
        }
        return {userId,status}
    }

    async __createToken(userId,loginexp){
        let sql = 'select * from t_user where id = ?';
        let user = await this.executeSqlFirst(sql,[userId]);
        let uToken = userId;

        let tokenParams = {
            [Constant.LOGIN_USER_KEY]: uToken,
            email: user.email,
            name: user.name,
            id: user['id'],
            nickName: user['nickName'],
            userNo:user['userNo']
        };

        //5.用户信息存redis
        let redisParams = {
            accountNonExpired: true,//账户是否未过期,过期无法验证
            accountNonLocked: true,//指定用户是否解锁,锁定的用户无法进行身份验证
            appToken: false,//是否appToken
            authorities: [],//
            credentialsNonExpired: true,//指示是否已过期的用户的凭据(密码),过期的凭据防止认证
            demoAccount: user.demoAccount ? true : false,//是否演示账号
            enabled: true,//用户状态
            expireTime: new Date(moment().add(Constant.cmsExpireTime, 'minutes')).getTime(),//过期时间
            lastRefreshTime: new Date().getTime(),//最新刷新token时间
            ipaddr: this.ctx.getIP(),
            loginLocation: this.ctx.getIpLocal(),
            loginTime: new Date().getTime(),
            token: uToken,
            "user": {
                "admin": false,
                "query": {}
            },
            userId: user.id,
            username: user.name ? user.name : user.nickName,
            userNo:user.userNo
        };


        await this.ctx.service.redis.set(Constant.LOGIN_TOKEN_KEY + uToken, JSON.stringify(redisParams), loginexp || 60 * 60 * 24 * 3);

        return this.ctx.createToken(tokenParams);
    }


}

module.exports = UserService;
